﻿using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using HomeRun.AspectCore.Strategies;
using HomeRun.Utils;

namespace HomeRun.AspectCore.Commands
{
    public class Command
    {
        private XElement m_xmlCommand = null;
        private IOperation m_operationStrategy = null;
        private string m_dataTableName;
        private List<CommandCondition> m_conditions = new List<CommandCondition>();
        private List<CommandAssignment> m_assignments = new List<CommandAssignment>();
        private List<string> m_backupRows = new List<string>();

        public Command(XElement xmlcmd)
        {
            //set xml command
            m_xmlCommand = xmlcmd;

            //get strategy
            string operation = xmlcmd.Elements("Operation").First().Attribute("name").Value;
            switch (operation)
            {
                case "CRE":
                    {
                        m_operationStrategy = new CREStrategy();
                        break;
                    }
                case "DEL":
                    {
                        m_operationStrategy = new DELStrategy();
                        break;
                    }
                case "UPD":
                    {
                        m_operationStrategy = new UPDStrategy();
                        break;
                    }
                default:
                    {
                        break;
                    }
            }

            //get datatable name
            m_dataTableName = xmlcmd.Elements("Datatable").First().Attribute("name").Value;

            //get conditions
            foreach (XElement element in xmlcmd.Elements("Conditions").First().Elements())
            {
                m_conditions.Add(new CommandCondition(element));
            }

            //get assignments
            foreach (XElement element in xmlcmd.Elements("Assignments").First().Elements())
            {
                m_assignments.Add(new CommandAssignment(element));
            }
        }


        public bool Execute()
        {
            Logger.LogCmd("Execute: " + m_xmlCommand.ToString());
            m_backupRows = m_operationStrategy.Execute(m_dataTableName, m_conditions, m_assignments);
            return (m_backupRows.Count > 0) ? true : false;
        }

        public bool Undo()
        {
            Logger.LogCmd("Undo: " + m_xmlCommand.ToString());
            return m_operationStrategy.Undo(m_backupRows);
        }
    }
}
